<template>
  <div class="login">
    <p class="login-title">朝夕后台管理系统</p>
    <div class="login-content">
      <div class="login-main">
        <div class="login-container">
          <el-form ref="ruleFormRef" label-width="120px" :rules="rules" class="demo-ruleForm" :model="userInfo">
            <el-form-item label="用户名" prop="account">
              <el-input v-model="userInfo.account" />
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="userInfo.password" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submit(ruleFormRef)"> 登录 </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { fetchLogin } from "@/http/apis";
import { setToken } from "@/utils/auth";
import { reactive, useTemplateRef } from "vue";
import { useRouter } from "vue-router";

const userInfo = reactive({
  account: "",
  password: "",
});

const rules = reactive({
  account: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const ruleFormRef = useTemplateRef("ruleFormRef");
const $router = useRouter();
const submit = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate(async (valid, fields) => {
    if (valid) {
      // Admin itlove123456
      const resp = await fetchLogin(userInfo);
      const { uid, token, msg } = resp.data;
      if (uid) {
        setToken(token);
        $router.push("/home");
      } else {
        alert(msg);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>
